import { defineStore } from 'pinia'
import { auth } from '../api'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || 'null'),
    userRole: localStorage.getItem('userRole') || 'user'
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.userRole === 'admin'
  },

  actions: {
    async login(credentials) {
      try {
        const response = await auth.login(credentials)
        this.token = response.token
        this.user = response.user
        this.userRole = response.user.role
        localStorage.setItem('token', response.token)
        localStorage.setItem('user', JSON.stringify(response.user))
        localStorage.setItem('userRole', response.user.role)
        return response
      } catch (error) {
        throw error
      }
    },

    async register(userData) {
      try {
        const response = await auth.register(userData)
        this.token = response.token
        this.user = response.user
        this.userRole = response.user.role
        localStorage.setItem('token', response.token)
        localStorage.setItem('user', JSON.stringify(response.user))
        localStorage.setItem('userRole', response.user.role)
        return response
      } catch (error) {
        throw error
      }
    },

    logout() {
      this.token = ''
      this.user = null
      this.userRole = 'user'
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('userRole')
    },

    async updateProfile(userData) {
      try {
        const response = await auth.updateProfile(userData)
        this.user = response.user
        localStorage.setItem('user', JSON.stringify(response.user))
        return response
      } catch (error) {
        throw error
      }
    }
  }
}) 